import { Component, OnInit } from '@angular/core';

import { ActivatedRoute, Router, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot, NavigationEnd } from '@angular/router';

import { Md5 } from 'ts-md5/dist/md5';

import { fadeIn, fadeOut, flyIn, flyOut } from "../common/animate.common";

import { User, ErrorMsg, Phone, PhoneErrorMsg } from '../models/user.model';

import { Check } from "../common/check";

import { LoginService } from "./login.service";

import { StorageService } from "../../app/common/storage.service";


@Component({
    templateUrl: './login.component-new.html',
    styleUrls: ['./login.component.css','./login.component-new.css'],
    animations: [fadeIn, fadeOut, flyIn, flyOut]
})

export class LoginComponent {

    private check: Check = new Check();
    private appid: string;
    private redirectUri: string;
    private timeOutId: any;
    private localStorage = window.localStorage ? window.localStorage : null;
    newPw: any;
    confirmPW: any;
    user: User = new User('default');
    phone: Phone = new Phone('default');
    error: ErrorMsg = new ErrorMsg();
    phoneError: PhoneErrorMsg = new ErrorMsg();
    hasCheckCode: boolean;
    hasPhoneCode: boolean;
    hasPhoneTextCode: boolean;
    checkCodeSrc: any = '';
    phoneTextCodeSrc: any = '';
    phoneTextCode: string = '';
    isActive = true;
    gottenPhoneCode = false;
    countdown: number = 60;
    remember: boolean;
    forgotMsg: string;
    isplay: boolean;
    forgotFlag: boolean = true;
    times: any;
    data: any;
    isPhone: boolean; // 是否是手机登录
    randomStr: any; // 随机数
    msgs: any;
    accountPw: string;
    imageCode: string;

    constructor(private service: LoginService, private router: Router, private storage: StorageService) { };

    ngOnInit() {
        this.randomStr = new Date().getTime();
        this.user.code = this.localStorage ? this.localStorage.getItem('account') : '';
        this.remember = this.user.code ? true : false;
        this.user.phoneVerifyCode = '';
        this.isPhone = false;
        this.getCheckCode('user');
    }
    
    private resultSucceed(data) {
        let InitPassword = '493779a4950422eb1121302af221d28d';
        let url = this.service.redirectUrl || "saas";
        let serviceUrl = data.data.facilitatorUrl || '';
        this.service.isLogin = true;
        this.localStorage && this.remember ? this.localStorage.setItem('account', this.user.code) : this.localStorage.removeItem('account');
        window.localStorage.setItem('rights', JSON.stringify(data.data));

        // window.localStorage.removeItem('remainCount'); // 如果登陆成功，则删除登陆次数
        Promise.all([this.service.getComDep({}),this.service.dic()]).then(data=>{
            this.storage.loadout();
           if(data[0].result && data[1].result){
                window.localStorage.setItem('dic', JSON.stringify(data[1].data || []));
                window.localStorage.setItem('org', JSON.stringify(data[0].data || []));
                // 根据服务商的不同状态跳转不同页面
                if(serviceUrl){
                    this.router.navigateByUrl(serviceUrl);return
                }
                
                if (this.user.accountPassword === InitPassword) {
                this.isplay = true; // 修改密码弹框
                this.newPw = ''; // 清空密码框
                this.confirmPW = '';
                this.forgotMsg = '';
                }else{
                    this.service.followUpLoginRemind().then(data => {});
                    this.router.navigateByUrl(url);
                    this.storage.isLogin = true;
                }
            }else{
                this.msgs = [];
                this.msgs.push({severity:'error', detail: '服务异常请刷新后重试'});
            } 
        }
        )
        // this.service.dic().then(data => {
        //     
        //     if (data.result) { 
        //         window.localStorage.setItem('dic', JSON.stringify(data.data));
        //         if (this.user.accountPassword === InitPassword) {
        //             this.isplay = true; // 修改密码弹框
        //             this.newPw = ''; // 清空密码框
        //             this.confirmPW = '';
        //             this.forgotMsg = '';
        //         } else {
        //             this.router.navigateByUrl(url);
        //         }
        //     } else {
        //        this.msgs = [];
        //        this.msgs.push({severity:'error', detail: '字典服务异常'});
        //     }
        // })
    }



    // 登录次数 登录3次-验证码出来 连续登陆8次-跳转手机登录
    private resultFalse(data) {
        if(data.data){
            if (+data.data.remainCount === 0) {
                // window.localStorage.setItem('remainCount', data.data.remainCount);
                // this.error.msg = data.msg;
                this.isPhone = true;
                this.phone.code = '';
                this.phone.phoneVerifyCode = ''; // 手机验证码
                this.phoneError.msg = "";
                return
            }
            if (+data.data.remainCount < 6) {
                this.isPhone = false; // 手机号登陆
                this.hasCheckCode = true; // 是否显示用户名验证码
                this.user.isCheckCode = ''; //用户名验证码
                // 随机数
                this.getCheckCode('user');
            }
        }
        this.error.msg = data.msg;
        this.getCheckCode('user');
        
    }

    private countDown() {
        this.countdown = 60;
        this.timeOutId = setInterval(() => {
            --this.countdown;
            this.countdown == 0 ? this.shutCountdown() : '';
        }, 1000)
    }
    private shutCountdown() {
        if (this.timeOutId) {
            clearInterval(this.timeOutId);
            this.gottenPhoneCode = false;
            this.countdown = 60;
        }
    }

    // 修改密码
    pwSubmit(newPw, confirmPW) {
        let InitPassword = '493779a4950422eb1121302af221d28d';
        let editNewPw = Md5.hashStr(newPw).toString();
        if(!newPw){
            this.forgotMsg = '请输入新密码';
            return;
        }
        if (!this.check.password(newPw)) {
            this.forgotMsg = '密码长度6~12位，数字+字母组合';
            return;
        } else {
            this.forgotMsg = '';
        }
        if(editNewPw === InitPassword){
            this.forgotMsg = '新密码与原始密码一致,请重新输入!';
            return;
        }
        if(!confirmPW){
            this.forgotMsg = '请输入确认密码';
            return;
        }
        if (newPw !== confirmPW) {
            this.forgotMsg = '确认密码与新密码不一致,请重新输入!';
            return;
        } else {
            this.forgotMsg = '';
        }

        if (this.phone.accountType === 1 || this.phone.accountType === 2) {
            this.data = {
                accountPasswords: Md5.hashStr(newPw).toString(),
                confirmPwds: Md5.hashStr(confirmPW).toString(),
                codes: this.user.code // 用户名或者手机号登录
            }
        } else if (this.phone.accountType === 3) {
            this.data = {
                accountPasswords: Md5.hashStr(newPw).toString(),
                confirmPwds: Md5.hashStr(confirmPW).toString(),
                codes: this.phone.code // 手机号登录
            }
        }

        let url = this.service.redirectUrl || "saas";
        this.storage.loading();
        this.service.resetPwd(this.data).then(
            data => {
                this.storage.loadout();
                if (data.result) {
                    this.msgs = [];
                    this.msgs.push({severity:'success', detail:'修改成功'});
                    this.service.followUpLoginRemind().then(data => {});
                    this.router.navigateByUrl(url);
                } else {
                    this.msgs = [];
                    this.msgs.push({severity:'error', detail: data.msg});
                }
            }
        )
    }

    login() {
        this.user.code = this.user.code ? this.user.code.trim() : '';
        // this.user.accountPw = this.user.accountPw ? this.user.accountPw.trim() : '';
        if(!this.user.code){
            this.error.msg = '请输入用户名/手机号';
            return;
        }
        if(!this.accountPw){
            this.error.msg = '请输入密码';
            return;
        }
        if(!this.imageCode){
            this.error.msg = '请输入图片验证码';
            return;
        }
        this.phone.accountType = 1; // 用户名登录-1 手机号登录-2
        if (this.check.phone(this.user.code)) {
            this.phone.accountType = 2;
            if (!this.check.phone(this.user.code)) {
                this.error.code = 1;
                this.error.msg = this.hasPhoneCode ? '请输入正确的手机号' : '请输入正确的账号/手机号';
                return;
            }
        } else {
            this.phone.accountType = 1;
        }

        if (!this.check.password(this.accountPw)) {
            this.error.code = 2;
            this.error.msg = '密码长度6~12位，数字和字母组合';
            return;
        }
        if (this.hasCheckCode && !this.user.isCheckCode){
            this.error.code = 3;
            this.error.msg = '请输入图片验证码';
            return;
        }
        if (this.hasCheckCode && (typeof this.user.isCheckCode === 'string' && this.user.isCheckCode.length != 4)) {
            this.error.code = 3;
            this.error.msg = '请输入正确的图片验证码';
            return;
        }
        this.user.accountPassword = Md5.hashStr(this.accountPw).toString();
        this.user.accountType = this.phone.accountType;
        this.user.randomStr = this.randomStr;
        this.storage.loading();
        let param = {account:this.user.code, password:this.user.accountPassword, imageCode: this.imageCode}
        this.service.login(param).then(
            data => {
                this.storage.loadout();
                if (data.result) {
                    // this.resultSucceed(data);
                    this.router.navigateByUrl("saas/home");
                    window.sessionStorage.setItem('isLogin', 'true');
                } else {
                    this.resultFalse(data);
                }
            }
        )
    }

    // phone-login
    phoneLogin() {
        this.phone.code = this.phone.code ? this.phone.code.trim() : '';
        if(!this.phone.code){
            this.phoneError.msg = '请输入手机号';
            return;
        }
        
        this.phone.accountType = 3;
        // this.phone.isCheckCode = false;
        if (!this.check.phone(this.phone.code)) {
            this.error.code = 1;
            this.phoneError.msg = '请输入正确的手机号';
            return;
        }
        if(!this.phone.phoneVerifyCode){
            this.phoneError.msg = '请获取并输入验证码';
            return;
        }
        if (typeof this.phone.phoneVerifyCode === 'string' && this.phone.phoneVerifyCode.length != 4) {
            this.phoneError.msg = '请输入正确的验证码';
            return;
        }
        if(this.hasPhoneTextCode && !this.phoneTextCode){
            this.phoneError.msg = '请输入图片验证码';
            return;
        }

        this.phone.isCheckCode = this.phoneTextCode ? this.phoneTextCode : 'false';
        this.phone.randomStr = this.randomStr;
        this.storage.loading();
        this.service.login(this.phone).then(
            data => {
                this.storage.loadout();
                // 登录3次-验证码出来
                if(data.data &&　data.data.remainCount){
                    if (data.data.remainCount >= 3) {
                        this.hasPhoneTextCode = true; //是否显示手机验证码
                        //this.phoneTextCode = ''; //手机验证码
                        this.getCheckCode('phone');
                    }                    
                }
                if (data.result) {
                    this.phoneResultSucceed(data);
                    window.sessionStorage.setItem('isLogin', 'true');
                } else {
                    this.phoneResultFalse(data);
                }
            }
        )

    }

    // phone-fail 
    phoneResultFalse(data) {
        // this.phone.code = '';
        this.phoneError.msg = data.msg;
        this.getCheckCode('phone');
    }

    // phone-seccess
    phoneResultSucceed(data) {
        window.localStorage.setItem('dic', JSON.stringify(data.data));
        // window.localStorage.removeItem('remainCount'); // 如果登陆成功，则删除登陆次数
        if (data.result) {
            this.isplay = true; // 修改密码弹框
            this.newPw = ''; // 清空密码框
            this.confirmPW = ''; // 清空确认密码框
            this.forgotMsg = ''; // 提示信息
        }

    }

    // 校验手机是否可用
    getPhoneCode(msg) {
        if (!this.check.phone(msg ? msg : this.phone.code)) {
            this.phoneError.code = msg ? this.phoneError.code : 1;
            this.phoneError.msg = msg ? this.phoneError.msg : '请输入正确的手机号';
            return;
        }
        this.service.employeeIsExistsByMobile({ mobile: msg ? msg : this.phone.code }).then(
            data => {
                if (data.result) {
                    this.phoneError.msg = msg ? this.phoneError.msg : '手机号未注册，请重新输入！';
                }else {
                    this.gottenPhoneCode = true; // 获取验证码按钮是否可点
                    this.phoneError.msg = '';
                    this.countDown();
                    this.smVerifyCodeSend(msg);
                }
            }
        )
    }

    // 获取手机号验证码
    smVerifyCodeSend(msg) {
        this.service.smVerifyCodeSend({ number: msg ? msg : this.phone.code }).then(
            data => {
                // // 登录3次-验证码出来
                // if (+data.data.remainCount === 0) {
                //     this.phoneError.msg = msg ? this.phoneError.msg : data.msg;
                //     return;
                // } else if (+data.data.remainCount < 3) {
                //     this.hasPhoneTextCode = true; //是否显示手机验证码
                //     this.phoneTextCode = ''; //手机验证码
                //     this.getCheckCode('phone');
                // }
                if (data.result) {
                    // this.gottenPhoneCode = true; // 获取验证码按钮是否可点
                    // this.phoneError.msg = '';
                    // this.countDown();
                } else {
                    this.phoneError.msg = msg ? this.phoneError.msg : data.msg;
                    // this.forgotMsg = msg ? data.msg : this.forgotMsg;
                }
            }
        )
    }

    getCheckCode(data) {
        if (data === 'phone') {
            this.phoneTextCodeSrc = this.service.getCheckCode(this.randomStr)
        }
        if (data === 'user') {
            this.checkCodeSrc = this.service.getCheckCode(this.randomStr)
        }
    }

    /* 
    忘记密码
    */
    next(num, code) {
        // this.service.checkPhoneVerifyCode({ code: num, phoneVerifyCode: code }).then(
        //     data => {
        //         data.result ? (this.forgotFlag = false) : (this.forgotMsg = data.msg);
        //     }
        // )
    }
    forgotPassword() {
        // this.isplay = true;
        // this.hasPhoneCode = false;
        this.router.navigate(['/login/forgetpw']);
    }
    close() {
        this.gottenPhoneCode = false;
        this.countdown = 60;
    }
}